<template>
  <div class="nurse">
    <!-- Breadcrumb 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>医院后台</el-breadcrumb-item>
      <el-breadcrumb-item>人员信息</el-breadcrumb-item>
      <el-breadcrumb-item>护士信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索患者的文本框 -->
    <el-input prefix-icon="el-icon-search" placeholder="请输入姓名查询" v-model="searchKeyword" clearable style="width: 180px; height: 28px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"></el-input>
    <el-card shadow="never" border="false">
      <!-- 卡片头部 -->
      <template #header>
        <div class="header">
          <span>共 {{ nurseDatelength }} 条记录</span>
          <el-button icon="el-icon-plus" size="small" type="warning" round @click="showAddNurseDialog" style="background-color: #eead0e">添加护士</el-button>
          <!-- 添加护士的对话框 -->
          <el-dialog title="添加/编辑护士" :visible.sync="dialogVisible" width="35%" @close="resetForm">
            <el-form ref="addNurseFormRef" :model="newNurse" label-width="70px">
              <el-form-item label="护士编号">
                <el-input v-model="newNurse.nurseID" style="width: auto" />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="newNurse.name" style="width: auto" />
              </el-form-item>
              <el-form-item label="科室">
                <el-select v-model="newNurse.department" clearable>
                  <el-option label="儿科" value="儿科" />
                  <el-option label="内科" value="内科" />
                  <el-option label="外科" value="外科" />
                  <el-option label="妇产科" value="妇产科" />
                </el-select>
              </el-form-item>
              <el-form-item label="职称">
                <el-select v-model="newNurse.title" clearable>
                  <el-option label="护师" value="护师" />
                  <el-option label="护士长" value="护士长" />
                  <el-option label="护士" value="护士" />
                  <el-option label="主管护师" value="主管护师" />
                </el-select>
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="newNurse.phone" style="width: auto" />
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="onDialogConfirm">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </template>

      <!-- 卡片的内容 -->
      <el-table stripe :data="filteredNurses" style="width: 100%" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
        <el-table-column prop="nurseID" label="护士编号（可点击）" fixed>
          <template slot-scope="scope">
            <a class="no-underline-link" @click="showRoomByNurseID(scope.row.nurseID)">
              {{ scope.row.nurseID }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="护士姓名"> </el-table-column>
        <el-table-column prop="department" label="护士科室"> </el-table-column>
        <el-table-column prop="title" label="护士职称"> </el-table-column>
        <el-table-column prop="phone" label="手机号码"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <!-- 添加编辑按钮的点击事件处理器 -->
            <el-button type="text" size="small" icon="el-icon-edit" @click="editNurse(scope.row)">编辑</el-button>
            <!-- 删除按钮部分 -->
            <el-button type="text" size="small" icon="el-icon-delete" style="color: red" @click="deleteNurse(scope.row.nurseID)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
//导入 vuex 中辅助函数
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
  name: 'nurse',
  data() {
    return {
      nurseDatelength:0,
      deleteConfirmVisible: false, // 控制删除确认对话框的显示
      deletingIndex: null, // 记录待删除项的索引
      dialogVisible: false,
      isEditing: false,
      searchKeyword: '',
      isNameClicked: false,
      newNurse: {
        nurseID: '',
        name: '',
        department: '',
        title: '',
        phone: '',
      },
    };
  },
  computed: {
    ...mapState('sickroom', ['room']),
    ...mapState('nurse', ['nurses', 'currentPage', 'pageSize']),
    ...mapState('nurse', ['filteredNurses']), // 从store中导入过滤后的护士列表
    ...mapGetters('nurse', ['nurseCount', 'changeDate']), //从store中导入

    // 修改filteredPatients计算属性以包含搜索过滤
    filteredNurses() {
      let nursesToFilter = this.nurses;

      // 根据状态筛选
      if (this.statusFilter) {
        nursesToFilter = nursesToFilter.filter(nurse => nurse.status === this.statusFilter);
      }

      // 根据搜索关键词筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        nursesToFilter = nursesToFilter.filter(nurse => {
          return nurse.name.toLowerCase().includes(keyword);
        });
      }
      this.nurseDatelength = nursesToFilter.length;
      return nursesToFilter;
    },
  },
  mounted() {
    this.nurseDatelength = this.nurses.length;
  },
  methods: {
    //查询护士
    onSearch() {
      this.$store.dispatch('nurse/searchNurses', this.searchKeyword);
    },

    //删除护士操作
    deleteNurse(nurseID) {
      this.$confirm('此操作将永久删除该医生信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用删除医生的 action
          this.$store
            .dispatch('nurse/DELETE_NURSE', nurseID)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '删除失败，请重试!',
              });
            });
        })
        .catch(() => {});
    },

    showAddNurseDialog() {
      this.dialogVisible = true; // 打开对话框
      this.isEditing = false; // 确保处于添加模式
      this.resetForm(); // 添加前重置表单，确保表单内容为空
    },

    // 编辑护士方法
    editNurse(nurse) {
      this.newNurse = { ...nurse }; // 复制对象以避免直接引用
      this.dialogVisible = true; // 打开对话框
      this.isEditing = true; // 设置为编辑模式
    },

    // 重置表单方法保持不变
    resetForm() {
      this.$refs['addNurseFormRef'].resetFields();
      this.isEditing = false; // 确保重置时回到非编辑状态
      this.newNurse = {
        nurseID: '',
        name: '',
        department: '',
        title: '',
        phone: '',
      };
    },

    addNurse() {
      // 这里添加提交表单逻辑，如验证数据后调用actions保存新护士数据
      this.$store
        .dispatch('nurse/addNurse', this.newNurse)
        .then(() => {
          this.dialogVisible = false; // 成功后关闭对话框
          this.$message.success('护士添加成功');
        })
        .catch(error => {
          this.$message.error('添加失败: ' + error.message);
        });
    },

    // 合并确认逻辑到一个方法
    onDialogConfirm() {
      // 判断是添加还是编辑
      if (this.isEditing) {
        // 更新护士信息
        this.$store
          .dispatch('nurse/updateNurse', this.newNurse)
          .then(() => {
            this.$message.success('护士信息更新成功');
            this.dialogVisible = false;
            this.resetForm();
            this.isEditing = false;
          })
          .catch(error => {
            this.$message.error('更新失败: ' + error.message);
          });
      } else {
        // 添加新护士
        this.$store
          .dispatch('nurse/addNurse', this.newNurse)
          .then(() => {
            this.$message.success('护士添加成功');
            this.dialogVisible = false;
            this.resetForm();
          })
          .catch(error => {
            this.$message.error('添加失败: ' + error.message);
          });
      }
    },

    showRoomByNurseID(nurseID) {
      // 从sickroom模块的getter获取病房信息
      const room = this.$store.getters['sickroom/getRoomByNurseID'](nurseID);

      if (room) {
        // 显示病房信息，这里以弹框为例
        this.$alert(`病房号: ${room.roomID}, 类型: ${room.type}`, '对接病房信息', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
          showClose: false, // 添加这一行
        });
      } else {
        this.$message.warning('未找到对应的病房信息');
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.nurse {
  .el-breadcrumb {
    margin-top: 10px;
    margin-bottom: 25px;
  }
  .el-card {
    margin-top: 25px;
    //卡片头部样式
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 16px;
    }
    //分页样式
    .el-pagination {
      margin-top: 20px;
      text-align: center;
    }
  }
  .no-underline-link {
    text-decoration: none;
    cursor: pointer;
    color: rgb(32, 142, 210);
    // 鼠标悬浮时颜色变化
    &:hover {
      color: rgba(213, 144, 17, 0.792); // 或者你希望的任何颜色
    }
  }
}
</style>